package com.atguigu.gmall.product.test;

import java.util.concurrent.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class CompletableFutureDemo {
//    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {
//            @Override
//            public Integer get() {
//                System.out.println(Thread.currentThread().getName() + "\t completableFuture");
//                //int i = 10 / 0;
//                return 1024;
//            }
//        });
//        CompletableFuture<Integer> fA = future.whenCompleteAsync(new BiConsumer<Integer, Throwable>() {
//            @Override
//            public void accept(Integer o, Throwable throwable) {
//                System.out.println(Thread.currentThread().getName() + "\t whenComplete");
//                System.out.println("-------o=" + o);
//                System.out.println("-------throwable=" + throwable);
//            }
//        });
//        CompletableFuture<Integer> fb = future.whenCompleteAsync(new BiConsumer<Integer, Throwable>() {
//            @Override
//            public void accept(Integer o, Throwable throwable) {
//                System.out.println(Thread.currentThread().getName() + "\t whenComplete");
//                System.out.println("-------o=" + o);
//                System.out.println("-------throwable=" + throwable);
//            }
//        });
////        System.out.println(future.get());
//    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> "hello");


        CompletableFuture<String> futureB = futureA.whenCompleteAsync(new BiConsumer<String, Throwable>() {
            @Override
            public void accept(String s, Throwable throwable) {
                delaySec(1);
                printCurrTime(s + " 第一个线程");
            }
        });
        CompletableFuture<String> futureC = futureA.whenCompleteAsync(new BiConsumer<String, Throwable>() {
            @Override
            public void accept(String s, Throwable throwable) {
                delaySec(3);
                printCurrTime(s + " 第二个线程");
            }
        });

    }

    private static void printCurrTime(String str) {
        System.out.println(str);
    }

    private static void delaySec(int i) {
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
